<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title></title>
	</head>
	<body>

	</body>
	<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
	<script>
		const gzhId = 'wxd1ce25ee70801e3b'; // 公众号appid
		const urla = 'https://gym.cytingchechang.com/getOpenId.html'; // 授权回调链接
		const urlb = encodeURIComponent(urla)
		console.log(urlb, '编码后的地址')
		init(); // 初始化 
		// 初始化效验
		function init() {
			if (!getUrlKey("code") && !sessionStorage.openId) {
				// 如果没有code和openId，就让跳转微信授权
				window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + gzhId + "&redirect_uri=" +
					urlb + "&response_type=code&scope=snsapi_userinfo";
			} else if (!sessionStorage.openId) {
				// 反之有code，没有openId就调用后台接口获取openId
				getOpenId();
			} else if (sessionStorage.openId) {
				// 如果有存在openId，那么直接跳转小程序
				jumpBtn(sessionStorage.openId);
			}
		}

		// 请求后台接口，获取openId
		function getOpenId() {
			var myHeaders = new Headers();
			myHeaders.append("Content-Type", "application/json");
			var raw = JSON.stringify({
				"code": getUrlKey("code")
			});
			console.log(raw, '公众号code')
			var requestOptions = {
				method: 'POST',
				headers: myHeaders,
				body: raw,
				redirect: 'follow'
			};
			
			fetch("https://gym.cytingchechang.com/prod-api/auth/wxMp", requestOptions)
				.then(response => response.text())
				.then(result => {
					let res = JSON.parse(result);
					if (res.code == '200') {
						console.log(res, '授权成功');
						sessionStorage.setItem("openId", res.data); // 存储openId
						jumpBtn(res.data); // 跳转微信小程序
					} else {
						console.log('授权失败');
						window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + gzhId +
							"&redirect_uri=" + urlb + "&response_type=code&scope=snsapi_userinfo";
					}
				})
				.catch(error => console.log('error', error));
		}

		// 跳转至小程序
		function jumpBtn(val) {
			// alert('val为传的openId: ' + val);
			// val为传的openId，小程序路径自行配置
			wx.miniProgram.navigateTo({
				url: `/pages/tabBar/passwordLogin/passwordLogin?gzhOpenId=` + val,
				success: (res) => {
					console.log(res, '跳转成功'); // 页面跳转成功的回调函数
				},
				fail: (err) => {
					console.log(err, '跳转失败'); // 页面跳转失败的回调函数
				},
				complete: () => {
					console.log('跳转尝试完成'); // 无论成功或失败都会执行
				}
			})
		}

		// 获取参数（http://www.sharedbk.com/post/188.html）
		function getUrlKey(name) {
			return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1]
				.replace(/\+/g, '%20')) || null
		}
	</script>
</html>